/***************************************************************
*
* DS_RAW_DATA.CPP
*
* simple automatic data buffer
***************************************************************/
#include "settings\ds_settings.h"
#include "ap\ap_comm.h"
#include "ds\ds_raw_data.h"
#include "ds\ds_bit_stream.h"

dsRAW_DATA::dsRAW_DATA(void) : pData(NULL), dataSize(0), isOwner(false)
{
}

dsRAW_DATA::dsRAW_DATA(const void *buf, int size) : pData(NULL), dataSize(0), isOwner(false)
{
   Copy(buf, size);   
}

dsRAW_DATA::dsRAW_DATA(const dsRAW_DATA &data) : pData(NULL), dataSize(0), isOwner(false)
{
   if (data.GetSize() > 0) {
      Copy(data.GetBuf(), data.GetSize());
   }
}

dsRAW_DATA& dsRAW_DATA::operator=(const dsRAW_DATA& src)
{
   if ( &src != this ) {
      Clear();

      Alloc(src.GetSize());
      Copy(src.GetBuf(), src.GetSize());
   }

   return *this;
}

dsRAW_DATA::~dsRAW_DATA(void)
{
   Clear();
}

void dsRAW_DATA::Clear(void)
{
   if (isOwner && pData != NULL) {
      free(pData);
   }

   isOwner  = false;
   pData    = NULL;
   dataSize     = 0;

   return;
}

void dsRAW_DATA::Copy(const void *buf, int size)
{
   Alloc(size);

   memcpy(pData, buf, size);

   return;
}

void dsRAW_DATA::MakeRef(void *buf, int size)
{
   Clear();

   pData    = (BYTE*)buf;
   dataSize = size;
   isOwner  = false;   

   return;
}

void dsRAW_DATA::Alloc(int size)
{
   Clear();

   pData    = (BYTE*)malloc(size);
   dataSize = size;
   isOwner  = true;
   
   return;
}

void *dsRAW_DATA::GetBuf(void)
{
   return pData;
}

const void *dsRAW_DATA::GetBuf(void) const
{
   return pData;
}

int dsRAW_DATA::GetSize(void) const
{
   return dataSize;
}

/**************************************************************
* dsRAW_DATA::Pack()
*
**************************************************************/
void dsRAW_DATA::Pack(ds::BIT_STREAM& stream) const
{
   STRONG_ASSERT(dataSize < 65536);
   WORD clamped = dataSize;
   stream.WriteBytes(sizeof(clamped), &clamped);
   stream.WriteBytes(dataSize, pData);
}

/**************************************************************
* dsRAW_DATA::Unpack()
*
**************************************************************/
void dsRAW_DATA::Unpack(ds::BIT_STREAM& stream)
{
   WORD size;
   stream.ReadBytes(sizeof(size), &size);
   Alloc(size);
   stream.ReadBytes(size, pData);
}
